<template>
  <div>
    <el-cascader
    filterable
      :class="{'cascader-input':initValueFlag}"
      v-model="value"
      :options="cascader_options"
      :props="cascader_props"
      :placeholder="initValue"
      @change="changeValue"
      >
    </el-cascader>
  </div>
</template>

<script>
// emit修改父级组件的值，简单的方法
// 1. :cityAreaValue.sync="form.area"  .sync监听
// 2. props接受 props: {cityAreaValue: {type:String,default:""}}
// 3. this.$emit("update:cityAreaValue",newData) update:指向cityAreaValue，后面跟新值

// import {GetCityPicker} from "@/api/common.js"

export default {
  data() {
    const _this = this
    return {
      initValue: "请选择省市区",
      initValueFlag: false,
      address: [],
      addressData: {},
      value: "",
      cascader_options: [],
      cascader_props: {
        lazy: true,
        // value: "value", // 级联默认value label对应显示
        // label: "label",
        lazyLoad(node, resolve) {
          const level = node.level // node.level 表示层级
          const requestData = {}
          const jsonType = { // 声明自定义配置
            0: {type: "province"},
            1: {type: "city",code:"province"},
            2: {type: "area",code:"city"}
          }
          if(jsonType[level].code) {
            requestData[`${jsonType[level].code}_code`] = node.value
          }
          requestData.type = jsonType[level].type
          GetCityPicker(requestData)
            .then((res) => {
              const data = res.data.data
              const type = jsonType[level].type.toUpperCase()
              data.forEach((i) => {
                i.value = i[`${type}_CODE`]
                i.label = i[`${type}_NAME`]
                if(level === 2) i.leaf = level >= 2 // leaf 阻止继续渲染，官方文档里有说明
              })
              _this.addressData[jsonType[level].type] = data
              resolve(data)
            })
          if(level !== 0) {
            _this.getAddress(node)
          }
        }
      },
    }
  },
  props: {
    cityAreaValue: {type:String,default:""},
    mapLocation: {type:Boolean,default:false} // 是否联动地图组件
  },
  methods: {
    initDefault(value) {
      if(value) {
        this.initValueFlag = true;
        this.initValue = value.split(",").join(" / ");
      }
    },
    getAddress(node) {
      if(node) {
        const index = node.level - 1
        this.address[index] = node.label
      }
      if(this.mapLocation) { // 是否联动地图
        this.$emit("setMapCenter", this.address.join(""))
      }
    },
    changeValue(value) {
      this.$emit("update:cityAreaValue",value.join())
      // 匹配最后一个，区级县级
      const lastCode = value[value.length - 1]
      const area = this.addressData.area.filter((i) => i.value === lastCode)[0]
      this.address[2] = area.label
      this.getAddress()
    },
    clear() {
      this.value = ""
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
